from flask import Blueprint, request, jsonify, g
from extensions import db
from models import Employee, Department, User
from utils import success, error, bad_request, forbidden
from datetime import datetime

# 创建员工管理API蓝图
employee_api = Blueprint('employee_api', __name__, url_prefix='/api/employees')

# 获取员工列表
@employee_api.route('/', methods=['GET'])
def get_employees():
    """获取员工列表"""
    try:
        # 检查用户权限
        current_user_id = g.user_id
        user = g.current_user
        
        if not user:
            return error(code=401, msg='用户不存在').to_response()
        
        # 获取查询参数
        page = request.args.get('page', 1, type=int)
        per_page = request.args.get('page_size', 10, type=int)  # 前端发送的是page_size
        department_id = request.args.get('department_id', type=int)
        search = request.args.get('search', '')
        
        # 构建查询
        query = Employee.query
        
        # 按部门筛选
        if department_id:
            query = query.filter(Employee.department_id == department_id)
        
        # 按姓名搜索
        if search:
            query = query.filter(Employee.name.contains(search))
        
        # 分页查询
        pagination = query.paginate(
            page=page, 
            per_page=per_page, 
            error_out=False
        )
        
        employees = []
        for emp in pagination.items:
            employee_data = {
                'id': emp.id,
                'name': emp.name,
                'gender': emp.gender,
                'phone': emp.phone,
                'position': emp.position,
                'department_id': emp.department_id,
                'department_name': emp.department.name if emp.department else None,
                'created_at': emp.created_at.isoformat(),
                'updated_at': emp.updated_at.isoformat()
            }
            employees.append(employee_data)
        
        return success(data={
            'employees': employees,
            'total': pagination.total,
            'pagination': {
                'page': pagination.page,
                'per_page': pagination.per_page,
                'total': pagination.total
            }
        }).to_response()
        
    except Exception as e:
        return error(msg=f'获取员工列表失败: {str(e)}').to_response()

# 创建员工
@employee_api.route('/', methods=['POST'])
def create_employee():
    """创建新员工"""
    try:
        # 检查用户权限
        current_user_id = g.user_id
        user = g.current_user
        
        if not user or user.role != 'admin':
            return forbidden(msg='权限不足').to_response()
        
        # 检查请求是否为JSON格式
        if not request.is_json:
            return bad_request('请求必须是JSON格式').to_response()
        
        data = request.get_json()
        
        # 验证必填字段
        required_fields = ['name', 'phone']
        for field in required_fields:
            if not data.get(field):
                return bad_request(msg=f'{field}字段不能为空').to_response()
        
        # 创建员工
        employee = Employee(
            name=data['name'],
            gender=data.get('gender'),
            phone=data['phone'],
            position=data.get('position'),
            department_id=data.get('department_id')
        )
        
        db.session.add(employee)
        db.session.commit()
        
        return success(data={'id': employee.id}, msg='员工创建成功').to_response()
        
    except Exception as e:
        db.session.rollback()
        return error(msg=f'创建员工失败: {str(e)}').to_response()

# 更新员工信息
@employee_api.route('/<int:employee_id>', methods=['PUT'])
def update_employee(employee_id):
    """更新员工信息"""
    try:
        # 检查用户权限
        current_user_id = g.user_id
        user = g.current_user
        
        if not user or user.role != 'admin':
            return forbidden(msg='权限不足').to_response()
        
        employee = Employee.query.get_or_404(employee_id)
        
        # 检查请求是否为JSON格式
        if not request.is_json:
            return bad_request('请求必须是JSON格式').to_response()
        
        data = request.get_json()
        
        # 更新员工信息
        if 'name' in data:
            employee.name = data['name']
        if 'gender' in data:
            employee.gender = data['gender']
        if 'phone' in data:
            employee.phone = data['phone']
        if 'position' in data:
            employee.position = data['position']
        if 'department_id' in data:
            employee.department_id = data['department_id']
        
        db.session.commit()
        
        return success(msg='员工信息更新成功').to_response()
        
    except Exception as e:
        db.session.rollback()
        return error(msg=f'更新员工信息失败: {str(e)}').to_response()

# 删除员工
@employee_api.route('/<int:employee_id>', methods=['DELETE'])
def delete_employee(employee_id):
    """删除员工"""
    try:
        # 检查用户权限
        current_user_id = g.user_id
        user = g.current_user
        
        if not user or user.role != 'admin':
            return forbidden(msg='权限不足').to_response()
        
        employee = Employee.query.get_or_404(employee_id)
        
        # 删除相关的用户记录（如果有）
        if employee.user_id:
            user_record = User.query.get(employee.user_id)
            if user_record:
                db.session.delete(user_record)
        
        db.session.delete(employee)
        db.session.commit()
        
        return success(msg='员工删除成功').to_response()
        
    except Exception as e:
        db.session.rollback()
        return error(msg=f'删除员工失败: {str(e)}').to_response()

# 获取部门列表（用于员工管理页面的下拉选择）
@employee_api.route('/departments', methods=['GET'])
def get_departments():
    """获取部门列表"""
    try:
        departments = Department.query.all()
        department_list = []
        
        for dept in departments:
            department_data = {
                'id': dept.id,
                'name': dept.name
            }
            department_list.append(department_data)
        
        return success(data=department_list).to_response()
        
    except Exception as e:
        return error(msg=f'获取部门列表失败: {str(e)}').to_response()

